﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;
using System.Web.Security;
using System.Configuration;
using System.Collections;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxClasses;

namespace TireService.Web.View.ServiceView
{
    public partial class ServicePlanning : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Initiate datalayer
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            { 
                // Bind data to container dropdownlist
                ddlContainer.DataSource = db.GetContainers();
                ddlContainer.ValueField = "ContainerId";
                ddlContainer.TextField = "ContainerNumber";
                ddlContainer.DataBind();

                // Select first container if no one preselected
                ddlContainer.SelectedIndex = 1;

                txtSelectedStartDate.Date = DateTime.Now; //Convert.ToDateTime("20-02-2011");
                txtSelectedEndDate.Date = txtSelectedStartDate.Date.AddMonths(3);
            }

            BindArea(db, Convert.ToInt32(ddlContainer.Value));

            // Bind tasks
            BindTasks(db, Convert.ToInt32(ddlContainer.Value));

            // Show weekplan on service cars
            BindWeekPlan(db, db.GetContainerServiceCars(Convert.ToInt32(ddlContainer.Value)), txtSelectedStartDate.Date, txtSelectedEndDate.Date);


            // Handles modal popup with capacity gridview
            //string columnIndexValue = ColumnIndex.Value, rowIndexValue = RowIndex.Value;
            //if (!string.IsNullOrEmpty(columnIndexValue) && !string.IsNullOrEmpty(rowIndexValue))
            //    BindDayPlan(columnIndexValue, rowIndexValue);
            pgWeekPlan.ClientSideEvents.CellClick = GetJSCellClickHandler();
        }

        protected string GetJSCellClickHandler()
        {
//            return string.Format(@"function (s, e) {{
//                var columnIndex = document.getElementById('{0}'),
//                rowIndex = document.getElementById('{1}');
//                columnIndex.value = e.ColumnIndex;
//                rowIndex.value = e.RowIndex;
//                gvDayPlan.SelectAllRowsOnPage(false);
//                gvDayPlan.PerformCallback('D');
//                
//            }}", ColumnIndex.ClientID, RowIndex.ClientID);

            return string.Format(@"function (s, e) {{
                LoadDayPlan(e.ColumnIndex,e.RowIndex);                
            }}");
        }

        private void BindArea(TireServiceDB db, int ContainerId)
        {
            if (ContainerId != 0)
            {
                var Areas = from p in db.ContainerServiceCarCoverages
                            join y in db.ServiceCarGeographicalAreaAllocations on p.ServiceCarId equals y.ServiceCarId into py
                            from z in py.DefaultIfEmpty()
                            join v in db.ServiceGeographicalAreas on z.ServiceGeoAreaId equals v.ServiceGeoAreaId into zv
                            from x in zv.DefaultIfEmpty()
                            where p.ContainerId == ContainerId & z.ScheduleDate != null
                            group x by new
                            {
                                x.ServiceGeoAreaId,
                                x.Description
                            }
                                into grp
                                select new 
                                { 
                                    grp.Key.ServiceGeoAreaId,
                                    Description = grp.Key.Description
                                };

                
                ddlArea.DataSource = Areas.ToList();
                ddlArea.ValueField = "ServiceGeoAreaId";
                ddlArea.TextField = "Description";
                ddlArea.DataBind();    
            }
        }

        private void BindTasks(TireServiceDB db, int ContainerId)
        {
            int[] tasktypestatus = new int[] { (int)Shared.TaskTypeStatus.ServiceDrive_Created, (int)Shared.TaskTypeStatus.ServiceDrive_Replan };

            if (ddlArea.SelectedIndex > 0)
            {
                // TODO: Make filtering on area possible (2013-03-03 - note made)
                //gvServiceDriveTasks.DataSource = db.TaskServiceDrivePlanningViews.Where(p => p.TaskTypeId == (int)Shared.TaskType.ServiceDrive & p.ContainerId == ContainerId & db.CountZipCodeInServiceGeographicalArea(Convert.ToInt32(ddlArea.Value), p.PrimaryZipCode) > 0).Where(d => tasktypestatus.Contains(d.TaskTypeStatusId)).ToList();

                var tasks = from p in db.TaskServiceDrivePlanningViews
                            join y in db.ContainerServiceCarCoverages on p.ContainerId equals y.ContainerId into py
                            from z in py.DefaultIfEmpty()
                            join v in db.ServiceCarGeographicalAreaAllocations on z.ServiceCarId equals v.ServiceCarId into zv
                            from x in zv.DefaultIfEmpty()
                            join w in db.ServiceGeographicalAreaZipCodeLists on x.ServiceGeoAreaId equals w.ServiceGeoAreaId into xw
                            from q in xw.DefaultIfEmpty()
                            where p.TaskTypeId == (int)Shared.TaskType.ServiceDrive & p.ContainerId == ContainerId & q.ServiceGeoAreaId == Convert.ToInt32(ddlArea.Value) & q.ZipCode == p.PrimaryZipCode & tasktypestatus.Contains(p.TaskTypeStatusId)
                            group p by new
                            {
                                p.TaskId,
                                p.DependentTaskId,
                                p.TaskTypeId,
                                p.TaskTypeDescription,
                                p.TaskTypeStatusId,
                                p.TaskTypeStatusDescription,
                                p.CustomerId,
                                p.CarId,
                                p.TireSetId, 
                                p.Createdate,
                                p.CompletionDate,
                                p.GenerateInvoice,
                                p.PrimaryAddress,
                                p.PrimaryZipCode,
                                p.PrimaryCity,
                                p.PrimaryCountryId,
                                p.PrimaryLongitude,
                                p.PrimaryLatitude,
                                p.CommentToAddress,
                                p.SecondaryAddress,
                                p.SecondaryZipCode,
                                p.SecondaryCity,
                                p.SecondaryCountryId,
                                p.SecondaryLongitude,
                                p.SecondaryLatitude,
                                p.CommentToSecondaryAddress,
                                p.RegistrationNumber,
                                p.CarStatusId,
                                p.TireTypeId,
                                p.TireSetStatusId,
                                p.ContainerCargoRoomId,
                                p.CargoRoomNumber,
                                p.ContainerId,
                                p.ContainerNumber,
                                p.Distance,
                                p.DistanceSecondary
                                
                            }
                                into grp
                                select new
                                {
                                    grp.Key.TaskId,
                                    grp.Key.DependentTaskId,
                                    grp.Key.TaskTypeId,
                                    grp.Key.TaskTypeDescription,
                                    grp.Key.TaskTypeStatusId,
                                    grp.Key.TaskTypeStatusDescription,
                                    grp.Key.CustomerId,
                                    grp.Key.CarId,
                                    grp.Key.TireSetId,
                                    grp.Key.Createdate,
                                    grp.Key.CompletionDate,
                                    grp.Key.GenerateInvoice,
                                    grp.Key.PrimaryAddress,
                                    grp.Key.PrimaryZipCode,
                                    grp.Key.PrimaryCity,
                                    grp.Key.PrimaryCountryId,
                                    grp.Key.PrimaryLongitude,
                                    grp.Key.PrimaryLatitude,
                                    grp.Key.CommentToAddress,
                                    grp.Key.SecondaryAddress,
                                    grp.Key.SecondaryZipCode,
                                    grp.Key.SecondaryCity,
                                    grp.Key.SecondaryCountryId,
                                    grp.Key.SecondaryLongitude,
                                    grp.Key.SecondaryLatitude,
                                    grp.Key.CommentToSecondaryAddress,
                                    grp.Key.RegistrationNumber,
                                    grp.Key.CarStatusId,
                                    grp.Key.TireTypeId,
                                    grp.Key.TireSetStatusId,
                                    grp.Key.ContainerCargoRoomId,
                                    grp.Key.CargoRoomNumber,
                                    grp.Key.ContainerId,
                                    grp.Key.ContainerNumber,
                                    grp.Key.Distance,
                                    grp.Key.DistanceSecondary
                                };

                gvServiceDriveTasks.DataSource = tasks.ToList();

                
            }
            else
            {
                gvServiceDriveTasks.DataSource = db.TaskServiceDrivePlanningViews.Where(p => p.TaskTypeId == (int)Shared.TaskType.ServiceDrive & p.ContainerId == ContainerId).Where(d => tasktypestatus.Contains(d.TaskTypeStatusId)).ToList();
            }
            
            gvServiceDriveTasks.DataBind();
        }

        /// <summary>
        /// Function that bind data to pivottable with service car capacity overview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="ServiceCarId">Array with services cars that should be included in capacity overview</param>
        /// <param name="Startdate">Startdate</param>
        /// <param name="Enddate">Enddate</param>
        protected void BindWeekPlan(TireServiceDB db, int[] ServiceCarId, DateTime Startdate, DateTime Enddate)
        {
            pgWeekPlan.DataSource = db.ServiceCarScheduleDetailViews.Where(p => p.ScheduleDate <= Enddate & p.ScheduleDate >= Startdate).Where(d => ServiceCarId.Contains(d.ServiceCarId)).ToList();
            pgWeekPlan.DataBind();
            
            
            
            //System.Globalization.DateTimeFormatInfo dfi = System.Globalization.DateTimeFormatInfo.CurrentInfo;
            //System.Globalization.Calendar cal = dfi.Calendar;
            //cal.GetWeekOfYear(DateTime.Now, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
        }

        /// <summary>
        /// Function that binds data to gridview with view on capacity for selected servicecar and day
        /// </summary>
        /// <param name="columnIndex"></param>
        /// <param name="rowIndex"></param>
        protected void BindDayPlan(string columnIndex, string rowIndex)
        {
            //gvDayPlan.DataSource = pgWeekPlan.CreateDrillDownDataSource(Int32.Parse(columnIndex), Int32.Parse(rowIndex));
            //gvDayPlan.DataBind();
        }

        protected void ddlArea_Callback(object source, CallbackEventArgsBase e)
        {
            // Initiate datalayer
            TireServiceDB db = new TireServiceDB();

            BindArea(db, Convert.ToInt32(e.Parameter));
        }


        protected void callBackLoadDayPlan_Callback(object sender, CallbackEventArgs e)
        {
            string[] param = e.Parameter.Split('|');

            var list = pgWeekPlan.CreateDrillDownDataSource(Int32.Parse(param[0]), Int32.Parse(param[1]));

            if (list.RowCount != 0)
            {
                int ServiceCarId = Convert.ToInt32(list[0]["ServiceCarId"]);
                DateTime ScheduleDate = Convert.ToDateTime(list[0]["ScheduleDate"]);

                e.Result = ServiceCarId.ToString() + "|" + ScheduleDate.ToShortDateString();
            }
        }

        protected void gvTaskDetail_DataSelect(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();
            ASPxGridView gvTaskDetail = (sender as ASPxGridView);
            gvTaskDetail.DataSource = db.GetTaskDetailsExtendedView(Convert.ToInt32((sender as ASPxGridView).GetMasterRowKeyValue()));
            //gvTaskDetail.DataBind();
        }

        public string GetTaskDetailCount(int TaskId)
        {
            TireServiceDB db = new TireServiceDB();
            return "Opgaver: " + db.CountTaskDetails(Convert.ToInt32(TaskId)).ToString();
        }

        //public DateTime GetLastOccurenceOfDay(DateTime value, DayOfWeek dayOfWeek)
        //{
        //    DateTime tempDate = value.AddDays(-1);
        //    while (tempDate.DayOfWeek != dayOfWeek)
        //    {
        //        tempDate = tempDate.AddDays(-1);
        //    }
        //    return tempDate;
        //}

        //public DateTime GetFirstDayOfWeek(int year, int weekNumber, DayOfWeek dayOfWeek)
        //{
        //    return GetLastOccurenceOfDay(new DateTime(year, 1, 1).AddDays(7 * weekNumber), dayOfWeek);
        //}

        //public DateTime GetFirstDayOfWeek(int year, int weekNumber)
        //{
        //    return GetFirstDayOfWeek(year, weekNumber, DayOfWeek.Monday);
        //} 


        /// <summary>
        /// Postback function that updates gridview with tasks for cars that need servicedrive
        /// </summary>
        protected void gvServiceDriveTasks_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Show service drive tasks
            BindTasks(db, Convert.ToInt32(ddlContainer.Value));
        }

        /// <summary>
        /// Postback function that updates overview of capacity on service cars
        /// </summary>
        protected void pgWeekPlan_CustomCallback(object sender, DevExpress.Web.ASPxPivotGrid.PivotGridCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Show capacity on servicecars
            BindWeekPlan(db, db.GetContainerServiceCars(Convert.ToInt32(ddlContainer.Value)), txtSelectedStartDate.Date, txtSelectedEndDate.Date);
        }

        ///// <summary>
        ///// Postback function that updates overview of capacity on specific service car and date
        ///// </summary>
        //protected void gvDayPlan_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        //{
        //    string[] param = e.Parameters.Split('|');
        //    if (param[0] != "D") return;
        //    BindDayPlan(ColumnIndex.Value, RowIndex.Value);
        //    gvDayPlan.PageIndex = 0;
        //}

        ///// <summary>
        ///// Gridview function that runs when databinding - Changes colors based on customerconfirmed value
        ///// </summary>
        //protected void gvDayPlan_HtmlRowPrepared(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableRowEventArgs e)
        //{
        //    if (e.RowType != DevExpress.Web.ASPxGridView.GridViewRowType.Data) return;

        //    int servicetype = Convert.ToInt32(gvDayPlan.GetRowValuesByKeyValue(e.KeyValue, "ScheduleDetailTypeId"));

        //    if (servicetype == (int)Shared.ScheduleDetailType.Available)
        //    {
        //        e.Row.BackColor = System.Drawing.Color.White;
        //    }
        //    if (servicetype == (int)Shared.ScheduleDetailType.Blocked)
        //    {
        //        e.Row.BackColor = System.Drawing.Color.Red;
        //    }
        //    if (servicetype == (int)Shared.ScheduleDetailType.ServiceDrive)
        //    {
        //        // Get customerconfirmed value - based on that rows will be formated
        //        bool CustomerConfirmed = Convert.ToBoolean(gvDayPlan.GetRowValuesByKeyValue(e.KeyValue, "CustomerConfirmed"));

        //        if (CustomerConfirmed)
        //        {
        //            e.Row.BackColor = System.Drawing.Color.DarkGreen;
        //        }
        //        else
        //        {

        //            e.Row.BackColor = System.Drawing.Color.Orange;
        //        }
        //    }
        //}

        ///// <summary>
        ///// Callback function that creates a single servicecar capacity record
        ///// </summary>
        //protected void callCreateSingleServiceCarCapacity_Callback(object sender, CallbackEventArgs e)
        //{
        //    // Get values (servicecarid, scheduledate, duration, overlap)
        //    string[] param = e.Parameter.Split('|');

        //    // Save new timeslot          
        //    int servicecarid = Convert.ToInt32(param[0]);
        //    DateTime datetime = Convert.ToDateTime(param[1]);

        //    TireServiceDB db = new TireServiceDB();

        //    ServiceCarSchedule schedule = db.GetServiceCarSchedule(servicecarid, datetime);

        //    ServiceCarScheduleDetail lastscheduledetail = schedule.ServiceCarScheduleDetails.OrderBy(p => p.SequenceNumber).Last();

        //    ServiceCarScheduleDetail scheduledetail = new ServiceCarScheduleDetail();
        //    schedule.ServiceCarScheduleDetails.Add(scheduledetail);
        //    scheduledetail.ScheduleDetailTypeId = (int)Shared.ScheduleDetailType.Available; 
        //    scheduledetail.SequenceNumber = lastscheduledetail.SequenceNumber + 1;
        //    scheduledetail.StartTime = lastscheduledetail.EndTime - TimeSpan.FromMinutes(Convert.ToInt32(param[3]));
        //    scheduledetail.EndTime = scheduledetail.StartTime.Add(TimeSpan.FromMinutes(Convert.ToInt32(param[2])));

        //    db.AddServiceCarScheduleDetail(scheduledetail);

        //    db.SubmitChanges();
        //}

        ///// <summary>
        ///// Callback function that bookes selected servicedrive task into selected servicedetail
        ///// </summary>
        //protected void callBookService_Callback(object sender, CallbackEventArgs e)
        //{
        //    // Get input parameters from client (0: taskid, 1: servicescheduledetailid, 2: usesecondaryaddress - true/false, 3: customerconfirmed - true/false, 4: note)
        //    string[] param = e.Parameter.Split('|');

        //    int TaskId = Convert.ToInt32(param[0]);
        //    int ServiceCarScheduleDetailId = Convert.ToInt32(param[1]);
        //    bool UseSecondaryAddress = Convert.ToBoolean(param[2]);
        //    bool CustomerConfirmed = Convert.ToBoolean(param[3]);
        //    string Note = param[4];

        //    TireServiceDB db = new TireServiceDB();

        //    Task task = db.GetTask(TaskId);
        //    if (task == null)
        //    {
        //        throw new ArgumentException("Ingen servicekørsel valgt - venligst vælg servicekørsel først.");
        //    }

        //    // Other validation of Task
        //    // TODO: Write needed code

        //    // Check if user has selected car from carneedservice gridview
        //    Car car = db.GetCar(Convert.ToInt32(task.CarId));
        //    if (car == null)
        //    {
        //        throw new ArgumentException("Ingen bil valgt angivet på servicekørsel - booking kan derfor ikke gennemføres.");
        //    }

        //    // Get servicecarscheduledetail record
        //    ServiceCarScheduleDetail scheduledetail = db.GetServiceCarScheduleDetail(ServiceCarScheduleDetailId);
        //    if (scheduledetail == null)
        //    {
        //        throw new ArgumentException("Valgt tidsrum eksistere ikke - venligst prøv igen.");
        //    }

        //    // Check if timeslot is "available"
        //    if (scheduledetail.ScheduleDetailTypeId != (int)Shared.ScheduleDetailType.Available)
        //    {
        //        throw new ArgumentException("Valgt tidsrum ikke ledigt - venligst vælg et andet.");
        //    }

        //    // Insert car on timeslot and update scheduledetail
        //    scheduledetail.CarId = car.CarId;
        //    scheduledetail.ToTireSetId = task.TireSetId;
        //    scheduledetail.CustomerConfirmed = CustomerConfirmed;
        //    if (UseSecondaryAddress)
        //    {
        //        scheduledetail.ToAddress = task.SecondaryAddress;
        //        scheduledetail.ToZipCode = task.SecondaryZipCode;
        //        scheduledetail.ToCity = task.SecondaryCity;
        //        scheduledetail.ToCountryId = task.SecondaryCountryId;
        //        scheduledetail.ToLatitude = task.SecondaryLatitude;
        //        scheduledetail.ToLongitude = task.SecondaryLongitude;
        //    }
        //    else
        //    {
        //        scheduledetail.ToAddress = task.PrimaryAddress;
        //        scheduledetail.ToZipCode = task.PrimaryZipCode;
        //        scheduledetail.ToCity = task.PrimaryCity;
        //        scheduledetail.ToCountryId = task.PrimaryCountryId;
        //        scheduledetail.ToLatitude = task.PrimaryLatitude;
        //        scheduledetail.ToLongitude = task.PrimaryLongitude;
        //    }

        //    scheduledetail.Note = Note;
        //    scheduledetail.ScheduleDetailTypeId = (int)Shared.ScheduleDetailType.ServiceDrive;

        //    // Fetch all TaskDetails to see if Task contain TireChange
        //    List<TaskDetail> taskdetails = db.GetTaskDetails(task.TaskId);

        //    foreach (TaskDetail taskdetail in taskdetails)
        //    {
        //        if (taskdetail.TaskDetailTypeId == (int)Shared.TaskDetailType.ServiceDrive_ChangeTire)
        //        {
        //            // Update car with new status        
        //            car.CarStatusId = (int)Shared.CarStatus.PlannedTireChange;
        //        }   
        //    }

        //    // Relate Task to ServiceCarScheduleDetail
        //    scheduledetail.TaskId = task.TaskId;

        //    // Update Task status
        //    task.TaskTypeStatusId = (int)Shared.TaskTypeStatus.ServiceDrive_Planned;

        //    // Submit changes to database
        //    db.SubmitChanges();

        //    // Dispose database connection
        //    db.Dispose();
        //}

        ///// <summary>
        ///// Callback function that deletes bookes servicedetail
        ///// </summary>
        //protected void callDeleteBookedService_Callback(object sender, CallbackEventArgs e)
        //{
        //    // Get input parameters from client (servicescheduledetailid)
        //    string[] param = e.Parameter.Split('|');

        //    int ServiceCarScheduleDetailId = Convert.ToInt32(param[0]);

        //    TireServiceDB db = new TireServiceDB();

        //    // Get servicecarscheduledetail record
        //    ServiceCarScheduleDetail scheduledetail = db.GetServiceCarScheduleDetail(ServiceCarScheduleDetailId);
        //    if (scheduledetail == null)
        //    {
        //        throw new ArgumentException("Valgt tidsrum eksistere ikke - venligst prøv igen.");
        //    }

        //    // Check if timeslot is booked or blocked
        //    if (scheduledetail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.Available)
        //    {
        //        throw new ArgumentException("Valgt tidsrum er ikke booket - venligst vælg et andet.");
        //    }

        //    if (scheduledetail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive)
        //    {
        //        // Get related task
        //        Task task = db.GetTask(Convert.ToInt32(scheduledetail.TaskId));

        //        // Change status on task
        //        task.TaskTypeStatusId = (int)Shared.TaskTypeStatus.ServiceDrive_Replan;

        //        // Fetch all TaskDetails to see if Task contain TireChange
        //        List<TaskDetail> taskdetails = db.GetTaskDetails(task.TaskId);

        //        foreach (TaskDetail taskdetail in taskdetails)
        //        {
        //            if (taskdetail.TaskDetailTypeId == (int)Shared.TaskDetailType.ServiceDrive_ChangeTire)
        //            {
        //                Car car = db.GetCar(Convert.ToInt32(task.CarId));

        //                // Update car with new status        
        //                car.CarStatusId = (int)Shared.CarStatus.AwaitsTireChangePlanning;
        //            }
        //        }
        //    }

        //    // Update timeslot - reset to available status
        //    scheduledetail.ScheduleDetailTypeId = (int)Shared.ScheduleDetailType.Available;
        //    scheduledetail.CarId = null;
        //    scheduledetail.FromTireSetId = null;
        //    scheduledetail.ToTireSetId = null;

        //    scheduledetail.ToAddress = null;
        //    scheduledetail.ToZipCode = null;
        //    scheduledetail.ToCity = null;
        //    scheduledetail.ToCountryId = null;
        //    scheduledetail.ToLatitude = null;
        //    scheduledetail.ToLongitude = null;

        //    scheduledetail.Note = null;
        //    scheduledetail.CustomerConfirmed = false;
        //    scheduledetail.TaskId = null;

        //    // Commit changes to database
        //    db.SubmitChanges();

        //    // Dispose database connection
        //    db.Dispose();
        //}

        ///// <summary>
        ///// Callback function that handles approval and blocking of dayplan records
        ///// </summary>
        //protected void callBackManageCustomerApproval_Callback(object sender, CallbackEventArgs e)
        //{
        //    // Get values (0: Actionparameter, 1-X: Array of servicecarscheduledetailid's)
        //    string[] param = e.Parameter.Split('|');

        //    // Instantiate database
        //    TireServiceDB db = new TireServiceDB();

        //    // Validate action to take
        //    if (Convert.ToString(param[0]) == "RequestApproval")
        //    {
        //        for (int i = 1; i < param.Length; i++)
        //        {
        //            SendConfirmationEmailToSelected(db, Convert.ToInt32(param[i]));
        //        }    
        //    }
        //    if (Convert.ToString(param[0]) == "CustomerApproved")
        //    {
        //        for (int i = 1; i < param.Length; i++)
        //        {
        //            CustomerApproved(db, Convert.ToInt32(param[i]), true);
        //        }
        //    }
        //    if (Convert.ToString(param[0]) == "RemoveApprovalOnSelected")
        //    {
        //        for (int i = 1; i < param.Length; i++)
        //        {
        //            CustomerApproved(db, Convert.ToInt32(param[i]), false);
        //        }
        //    }
        //    if (Convert.ToString(param[0]) == "AddBlockOnSelected")
        //    {
        //        for (int i = 1; i < param.Length; i++)
        //        {
        //            ServiceCarScheduleDetail detail = db.GetServiceCarScheduleDetail(Convert.ToInt32(param[i]));

        //            if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.Available)
        //            {
        //                detail.ScheduleDetailTypeId = (int)Shared.ScheduleDetailType.Blocked;
        //                detail.Note = "Tidsrum blokeret";
        //            }
        //        }
        //    }

        //    // Commit changes to database
        //    db.SubmitChanges();

        //    // Dispose database connection
        //    db.Dispose();
        //}

        ///// <summary>
        ///// Function that sends confirmation email to selected customer
        ///// </summary>
        ///// <param name="db">Connection to database</param>
        ///// <param name="ServiceCarScheduleDetailId">Id on booking to send email for</param>
        //private void SendConfirmationEmailToSelected(TireServiceDB db, int ServiceCarScheduleDetailId)
        //{
        //    // Fecth detail
        //    ServiceCarScheduleDetailView detail = db.ServiceCarScheduleDetailViews.SingleOrDefault(p => p.ServiceCarScheduleDetailId == ServiceCarScheduleDetailId);

        //    if (detail != null)
        //    {
        //        //if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.TireChange)
        //        if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive)
        //        {
        //            // Send email
        //            SendConfirmationEmail(db, detail);
        //        }
        //    }
        //}

        ///// <summary>
        ///// Function that change confirmation on servicedetail for customer
        ///// </summary>
        ///// <param name="db">Connection to database</param>
        ///// <param name="ServiceCarScheduleDetailId">Id on booking to set as customer confirmed/not confirmed</param>
        ///// <param name="CustomerConfirmed">True/False value indicating if customer confirmed booking</param>
        //private void CustomerApproved(TireServiceDB db, int ServiceCarScheduleDetailId, bool CustomerConfirmed)
        //{
        //    // Fecth detail to update
        //    ServiceCarScheduleDetail detail = db.GetServiceCarScheduleDetail(ServiceCarScheduleDetailId);

        //    if (detail != null)
        //    {
        //        //if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.TireChange)
        //        if (detail.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive)
        //        {
        //            // Update detail
        //            detail.CustomerConfirmed = CustomerConfirmed;
        //        }
        //    }
        //}

        ///// <summary>
        ///// Function that sends email to customer for a specific servicedetail
        ///// </summary>
        ///// <param name="db">Database connection</param>
        ///// <param name="scheduledetail">Servicedetail</param>
        //private void SendConfirmationEmail(TireServiceDB db, ServiceCarScheduleDetailView scheduledetail)
        //{
        //    // Send email
        //    SendEmail(scheduledetail.Email, scheduledetail.Name, scheduledetail.TireTypeDescription, scheduledetail.ScheduleDate.ToShortDateString(), scheduledetail.StartTime.ToString() + "-" + scheduledetail.EndTime.ToString(), scheduledetail.ToAddress, scheduledetail.ToZipCode, scheduledetail.ToCity, scheduledetail.DetailGuid.ToString(), scheduledetail.CustomerId.ToString(), scheduledetail.SubscriptionId.ToString(), scheduledetail.CustomerSubscriptionId.ToString());

        //    // Update serviceschedule detail
        //    ServiceCarScheduleDetail updatescheduledetail = db.GetServiceCarScheduleDetail(scheduledetail.ServiceCarScheduleDetailId);
        //    updatescheduledetail.CustomerEmailSendCount = updatescheduledetail.CustomerEmailSendCount + 1;
        //}

        ///// <summary>
        ///// Function that sends email to customer with planned service date, time and location and link for confirming or declining planned service
        ///// </summary>
        ///// <param name="CustomerEmail">Customer email that this email will be send to</param>
        ///// <param name="CustomerName">Name on customer</param>
        ///// <param name="TireSetType">Tiretype description (Winther/Summer)</param>
        ///// <param name="ScheduleDate">Scheduledate for the service</param>
        ///// <param name="TimeSpan">Timespan for the service</param>
        ///// <param name="Address">Address for service</param>
        ///// <param name="ZipCode">ZipCode for service</param>
        ///// <param name="City">City for service</param>
        ///// <param name="DetailGuid">Unik id for serviceschedule detail - used in email links</param>
        //private void SendEmail(string CustomerEmail, string CustomerName, string TireSetType, string ScheduleDate, string TimeSpan, string Address, string ZipCode, string City, string DetailGuid, string CustomerId, string SubscriptionId, string CustomerSubscriptionId)
        //{
        //    string Subject = "Booking af tid til hjulskift (Abonnement " + CustomerId + "-" + SubscriptionId + "-" + CustomerSubscriptionId + ")";
        //    string CustomerApprovalLink = ConfigurationManager.AppSettings["CustomerConfirmationURL"].ToString() + "?ApprovalId=" + DetailGuid;
        //    string CustomerDisapprovalLink = ConfigurationManager.AppSettings["CustomerConfirmationURL"].ToString() + "?ApprovalId=" + DetailGuid + "&Approve=false";
        //    bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
        //    Shared email = new Shared();

        //    Hashtable templateVars = new Hashtable();

        //    // Send email to customer
        //    templateVars.Add("CustomerName", CustomerName);
        //    templateVars.Add("TireSetType", TireSetType);
        //    templateVars.Add("ScheduleDate", ScheduleDate);
        //    templateVars.Add("TimeSpan", TimeSpan);
        //    templateVars.Add("Address", Address);
        //    templateVars.Add("ZipCode", ZipCode);
        //    templateVars.Add("City", City);
        //    templateVars.Add("CustomerApprovalLink", CustomerApprovalLink);
        //    templateVars.Add("CustomerDisapprovalLink", CustomerDisapprovalLink);
        //    Shared.Parser parser = new Shared.Parser(Server.MapPath("~/Reports/HtmlTemplates/CustomerEmail_ServiceSchedulePlan.htm"), templateVars);

        //    MembershipUser user = Membership.GetUser();

        //    email.SendEmail(CustomerEmail, ConfigurationManager.AppSettings["EmailAddress"].ToString(), parser.Parse(), Subject, true, test, user.Email, null, null, Convert.ToInt32(CustomerId), new Guid(user.ProviderUserKey.ToString()));
        //}

    }
}